﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace SoftwareLogistics.SharepointClient.Library.Models
{
    public class SPQuery
    {
        public SPQuery()
        {
            SubQueries = new List<SPQuery>();
            OrderByClause = new List<SPOrderBy>();
            IsDefault = false;
        }

        public bool IsDefault { get; set; }

        public enum QueryTypes
        {
            And,
            Or
        }

        public QueryTypes QueryType;
        
        public void AddAndClause(params SPWhereClause[] args)
        {
            Clauses = new List<SPWhereClause>();
            var subQuery = new SPQuery { Clauses = new List<SPWhereClause>(), QueryType = QueryTypes.And };
            foreach(var arg in args)
                subQuery.Clauses.Add(arg);

            SubQueries.Add(subQuery);            
        }

        public void AddOrClause(params SPWhereClause[] args)
        {
            Clauses = new List<SPWhereClause>();
            var subQuery = new SPQuery();
            subQuery.QueryType = QueryTypes.Or;
            foreach (var arg in args)
                subQuery.Clauses.Add(arg);

            SubQueries.Add(subQuery);
        }

        public string Name { get; set; }
        public List<SPOrderBy> OrderByClause{ get; set; }
        public SPWhereClause WhereClause {get; set;}
        public List<SPWhereClause> Clauses { get; set; }
        public List<SPQuery> SubQueries { get; set; }

        public string OrderBy { get; set; }

        public XElement GetSubqueryElement()
        {
            var element = new XElement(QueryType == QueryTypes.And ? "And" : "Or");
            Clauses.ForEach(ele => element.Add(ele.GetXML()));
            return element;
        }

        public XElement GetElement()
        {
            if (WhereClause == null && SubQueries == null && OrderByClause == null)
                return null;

            var element = new XElement("Query");
            if (OrderByClause.Count > 0)
            {
                var orderByElement = new XElement("OrderBy");
                OrderByClause.ForEach(ele => orderByElement.Add(ele.GetXML()));
                element.Add(orderByElement);
            }

            var whereElement = new XElement("Where");

            if(SubQueries != null)
                SubQueries.ForEach(ele => whereElement.Add(ele.GetSubqueryElement()));

            if (WhereClause != null)
                whereElement.Add(WhereClause.GetXML());

            element.Add(whereElement);

            return element;
        }
    }
}
